#!/usr/bin/env python

import os
import sys
import re

# regular expressions
re_mp3 = re.compile(r'.*mp3$')
re_genre = re.compile(r'\(.*\)')

from MP3_DB import MP3_DataBase

# import eyeD3
# from eyeD3 import Tag, TagException, GenreException, Mp3Exception

from eyeD3 import Tag, TagException, GenreException
tag = Tag()

if len(sys.argv) < 2 :
    print 'Usage: ',sys.argv[0],' <root directory>'
    sys.exit(1)

RootDir = sys.argv[1]
if not os.path.isdir(RootDir) :
    print 'Usage: ',sys.argv[0],' <root directory>'
    sys.exit(1)

# Initialize Database
DB = MP3_DataBase()

# setup tree
from xml.etree.ElementTree import Element, SubElement, tostring

# root element
FileName = RootDir + '.xml'
root = Element('Root',{'file':FileName})
log = open(RootDir + '.log','w')

ArtistOld = ''
AlbumOld = ''
count=0
GenreStr = ''

try:
    # walk the directory
    for Root,Dirs,Files in os.walk(RootDir):
        # find the MP3 files
        for File in Files:
            m = re_mp3.match(File,re.I)

            # ignore non-MP3 files
            if ( not m ):
                continue

            # count of MP3 files
            count += 1
            if ( not (count % 100) ):
                print count

            # get ID3 tag
            Path = Root + '/' + File
            try:
                if ( tag.link(Path) == False ):
                    print >> log, File,': no tag found'
                    continue
            # log tag exceptions and continue
            except TagException as TE:
                print >> log, 'TagException: ',TE
                print >> log, 'File = ',Path
                continue
            
            Artist = tag.getArtist().encode(errors='replace')
            if ( not len(Artist) ): # filter garbage
                continue

            # new artist?
            NewArtist = False
            if ( Artist != ArtistOld ):
                ArtistElem = SubElement(root,'artist',{'name':Artist})
                ArtistOld = Artist
                NewArtist = True

            Album = tag.getAlbum().encode(errors='replace')
            if ( not len(Album) ): # filter garbage
                continue
            # new album or new artist?
            if ( Album != AlbumOld or NewArtist ):
                AlbumElem = SubElement(ArtistElem,'album',{'name':Album})
                AlbumOld = Album

            # genre
            try:
                Genre = tag.getGenre()
                if ( Genre ):
                    AlbumElem.set('genre',re_genre.sub('',str(Genre)))

            except GenreException as GE:
                print 'Genre Exception: ',GE

            # CDID = tag.getCDID()
            # if ( len(CDID) ):
            #     print CDID
            #     AlbumElem.set('CDID',str(CDID))

            # Assume tracks are unique
            Title = tag.getTitle().encode(errors='replace')
            if ( not len(Title) ): # filter garbage
                continue

            TrackElem = SubElement(AlbumElem,'track',{'title':Title})
            # composer
            Composer = tag.getArtist('COMPOSER_FID').encode(errors='replace')
            if ( len(Composer) ):
                TrackElem.set('composer',Composer)
            # track numbers
            Num = tag.getTrackNum()[0]
            if ( Num ):
                TrackElem.set('num','%d' % Num )
            TotalNum = tag.getTrackNum()[1]
            if ( TotalNum ):
                AlbumElem.set('tracks','%d' % TotalNum )

            # add track to database
            DB.AddSong(Artist,Album,Title,Num,TotalNum)

#except Mp3Exception as ME:
#    print 'MP3 Exception: ',ME

except Exception as Ex:
    print 'Exception: ',Ex

from xml.dom import minidom

def prettify(elem):
    xmlstr = tostring(elem,'utf-8')
    reparsed = minidom.parseString(xmlstr)
    # reparsed = minidom.parseString(tostring(elem,'latin-1'))
    return reparsed.toprettyxml(indent='  ')

# XML output
sys.stdout = open(FileName,'w')
print prettify(root)

# add information to database

import MP3_DB

# get all the artist names
ArtistElem = root
